package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;

/*
* 蓝色兄弟
* */
@Slf4j
public class Plugin_ECARD_P038 implements ChannelService {


    @Override
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }

    @Override
    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data) {
        try {
            HashMap<String, String> SubmitParams = new HashMap<>();
            String appId = apiConfig.getString("AppId");
            String key = apiConfig.getString("AppKey");
            String submitUrl = apiConfig.getString("SubmitUrl");
            String callBackUrl = apiConfig.getString("CallBackUrl");
            String accountVal = String.valueOf(data.get("AccountVal"));

            SubmitParams.put("merchantId",appId);
            SubmitParams.put("outTradeNo", String.valueOf(data.get("ChannelOrderCode")));
            SubmitParams.put("productId",String.valueOf(data.get("SUPProductId")));
            SubmitParams.put("rechargeAccount",accountVal);
            int type = matchAccountType(accountVal);

            SubmitParams.put("accountType",String.valueOf(type));
            SubmitParams.put("number","1");
            long timestamp = System.currentTimeMillis();
            long seconds = Math.floorDiv(timestamp, 1000);
            String formattedTimestamp = String.format("%010d", seconds);
            SubmitParams.put("timeStamp",formattedTimestamp);
            SubmitParams.put("notifyUrl",callBackUrl);
            String sign = generateSign(SubmitParams, key);
            SubmitParams.put("sign",sign);
            SubmitParams.put("version","1.0");

            String respStr = HttpTool.HttpPost(submitUrl, SubmitParams);
            JSONObject parseObject = JSONObject.parseObject(respStr);
            String code = parseObject.getString("code");
            String message = parseObject.getString("message");
            if (code.equals("2000") || code.equals("0000")||code.equals("1005")){
                return ChannelResult.IN_PROCESS("充值中");
            }
            if (code.equals("1012")||code.equals("1999")) {
                return ChannelResult.error(message);
            }
            return ChannelResult.FAILED(message);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("蓝色兄弟提单接口错误：",e);
            return  ChannelResult.error("蓝色兄弟提单接口错误");
        }

    }

    @Override
    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {
        try {
            String appId = apiConfig.getString("AppId");
            String key = apiConfig.getString("AppKey");
            String queryUrl = apiConfig.getString("QueryUrl");

            HashMap<String, String> queryParams = new HashMap<>();

            queryParams.put("merchantId",appId);
            queryParams.put("outTradeNo", String.valueOf(data.get("ChannelOrderCode")));
            long timestamp = System.currentTimeMillis();
            long seconds = Math.floorDiv(timestamp, 1000);
            String formattedTimestamp = String.format("%010d", seconds);
            queryParams.put("timeStamp",formattedTimestamp);
            String sign = generateSign(queryParams, key);
            queryParams.put("sign",sign);
            queryParams.put("version","1.0");

            String respStr = HttpTool.HttpPost(queryUrl, queryParams);
            JSONObject parseObject = JSONObject.parseObject(respStr);
            String code = parseObject.getString("code");
            String message = parseObject.getString("message");
            if (code.equals("0000")){
                String status = parseObject.getString("status");
                if (status.equals("01")) {
                    return ChannelResult.success("充值成功");
                }
                if (status.equals("02")) {
                    return ChannelResult.IN_PROCESS("充值中");
                }
                if (status.equals("03")) {
                    return ChannelResult.FAILED(message);
                }
            }
            if (code.equals("1012")){
                return ChannelResult.FAILED(message);
            }
            return ChannelResult.error(message);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("蓝色兄弟查询接口错误：",e);
            return  ChannelResult.error("蓝色兄弟查询接口错误");
        }
    }


    @Override
    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");
    }

    public static String generateSign(Map<String, String> params, String key) {
        // 1. 将参数按照键的ASCII码从小到大排序（字典序）
        Map<String, String> sortedParams = new TreeMap<>(params);

        // 2. 将非空参数值按照URL键值对的格式拼接成字符串stringA
        StringBuilder stringA = new StringBuilder();
        for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
            if (!entry.getValue().isEmpty()) {
                stringA.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        stringA.append("key").append("=").append(key);

        return md5Encrypt(stringA.toString());

    }

    public static String md5Encrypt(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                hexString.append(String.format("%02X", b));
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }


    public static int matchAccountType(String account) {
        String phonePattern = "^1[3456789]\\d{9}$";
        String emailPattern = "^([\\w-]+@[\\w-]+\\.[\\w-]+)$";
        String qqPattern = "^([1-3]\\d{4,9}|[1-9]\\d{4,8})$";
        String weChatPattern = "^[a-zA-Z]([-_a-zA-Z0-9]{5,19})$";
        Pattern phonePatternObj = Pattern.compile(phonePattern);
        Pattern emailPatternObj = Pattern.compile(emailPattern);
        Pattern qqPatternObj = Pattern.compile(qqPattern);
        Pattern weChatPatternObj = Pattern.compile(weChatPattern);
        if (phonePatternObj.matcher(account).matches()) {
            return 1; // 手机号
        } else if (emailPatternObj.matcher(account).matches()) {
            return 0; // 其他
        } else if (qqPatternObj.matcher(account).matches()) {
            return 2; // QQ号
        } else if (weChatPatternObj.matcher(account).matches()) {
            return 0; // 微信号
        } else {
            return 0; // 其他
        }
    }


}
